import * as vscode from 'vscode';

let collection: vscode.DiagnosticCollection | undefined;

export function initDiagnostics(context: vscode.ExtensionContext): void {
    if (!collection) {
        collection = vscode.languages.createDiagnosticCollection('magic-api');
        context.subscriptions.push(collection);
    }
}

function getBaseFileName(uri: vscode.Uri): string {
    // 支持 magic-api:/ 与 file:/ 两种 scheme
    const path = uri.path.replace(/^\/+/, '');
    const last = path.split('/').pop() || '';
    let name = last;
    if (name.endsWith('.ms')) name = name.replace(/\.ms$/, '');
    else if (name.includes('.')) name = name.substring(0, name.lastIndexOf('.'));
    return name;
}

export function addFileError(uri: vscode.Uri, message: string): void {
    if (!collection) return;
    const base = getBaseFileName(uri);
    const hint = `请检查文件中是否有遗漏的必填项：.${base}.meta.json文件`;
    const diag = new vscode.Diagnostic(new vscode.Range(0, 0, 0, 0), `${message}。${hint}`, vscode.DiagnosticSeverity.Error);
    diag.source = 'magic-api';
    collection.set(uri, [diag]);
}

export function clearFileErrors(uri: vscode.Uri): void {
    if (!collection) return;
    collection.delete(uri);
}